package com.yunji.base.business;

import com.yunji.base.cache.BaseCache;
import com.yunji.common.base.BaseBusiness;
import com.yunji.common.enums.common.UserType;
import com.yunji.common.model.domain.SysRoleDO;
import com.yunji.common.model.domain.SysUserDO;
import com.yunji.common.model.dto.LoginInfo;
import com.yunji.common.utils.StringUtils;
import com.yunji.common.utils.bean.BeanUtils;
import com.yunji.common.utils.uuid.UUIDUtils;
import com.yunji.system.context.SystemContext;
import com.yunji.system.service.ISysRoleService;
import com.yunji.system.service.ISysUserService;
import com.yunji.system.service.SysPermissionService;
import com.yunji.system.service.TokenService;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * @version 1.0
 * @Project: yunji-coffee
 * @Package com.yunji.user.business
 * @FileName MultiRoleBusiness.java
 * @Copyright Copyright © 2024 云集互联. All Rights Reserved
 * Company		com
 * @CreateTime 2024-08-20 14:10:31
 * @Description 多角色处理
 * @Modification Author                    History Time			Version				Description
 * --------------------------------------------------------------------------------
 * HuaAo0803@163.com	2024-08-20 14:10:31		1.0					1.0 Version
 * @since JDK 1.8.0_202
 */
@Component
public class MultiRoleBusiness extends BaseBusiness {
    @Resource
    TokenService tokenService;

    @Resource
    ISysRoleService roleService;

    @Resource
    ISysUserService userService;

    @Resource
    SysPermissionService permissionService;

    private static final String CREATE_ERROR_NAME = "新增角色'{}'失败，角色名称已存在";
    private static final String CREATE_ERROR_CODE = "新增角色'{}'失败，角色权限已存在";
    private static final String UPDATE_ERROR_NAME = "修改角色'{}'失败，角色名称已存在";

    /**
     * @param role 角色信息参数
     * @return List<SysRole> 角色信息列表
     * @Title search
     * @Intro 查询角色信息列表
     * @Date 2024-08-20 14:45:05.630
     */
    public List<SysRoleDO> search(SysRoleDO role) {
        LoginInfo user = tokenService.getUser();
        Long belongId = user.getBelongId();
        String userType = user.getUserType();
        String userText = UserType.getText(userType);
        logs.info("【新增角色】当前用户所属ID:{},用户类型={}:{}", belongId, userType, userText);
        role.setBelongId(belongId);
        return roleService.searchRoleList(role);
    }

    /**
     * @param id 角色信息ID
     * @return Role 角色信息详情
     * @Title select
     * @Intro 获取角色信息详情
     * @Date 2024-08-20 14:45:05.630
     */
    public SysRoleDO select(Long id) {
        return roleService.selectRoleById(id);
    }

    /**
     * @param role 角色信息
     * @Title create
     * @Intro 创建角色信息
     * @Date 2024-08-20 14:45:05.630
     */
    public Long create(SysRoleDO role) {
        String name = role.getRoleName();
        logs.info("【新增角色】角色名称:{}", name);

        String roleKey = UUIDUtils.quickUUID();
        role.setRoleKey(roleKey);
        Assert.isTrue(roleService.checkRoleKeyUnique(role), StringUtils.format(CREATE_ERROR_CODE, name));

        LoginInfo user = tokenService.getUser();
        logs.info("【新增角色】当前用户信息:{}", user);
        Long belongId = user.getBelongId();
        String userType = user.getUserType();
        String userText = UserType.getText(userType);
        logs.info("【新增角色】当前用户所属ID:{},用户类型={}:{}", belongId, userType, userText);
        role.setBelongId(belongId);

        role.setCreateBy(SystemContext.getUsername());
        Assert.isTrue((roleService.insertRole(role) > 0), "新增失败");

        return role.getRoleId();
    }

    /**
     * @param role 角色信息
     * @Title update
     * @Intro 更新角色信息
     * @Date 2024-08-20 14:45:05.630
     */
    public void update(SysRoleDO role) {
        Long roleId = role.getRoleId();
        String name = role.getRoleName();
        logs.info("【修改角色】角色ID:{}, 角色名称:{}", roleId, name);

        Assert.isTrue(BeanUtils.isNotNull(roleId), "未找到角色信息");
        SysRoleDO origin = roleService.selectRoleById(roleId);
        Assert.isTrue(BeanUtils.isNotNull(origin), "未找到角色信息");
        role.setRoleKey(origin.getRoleKey());

        roleService.checkRoleAllowed(role);

        LoginInfo info = tokenService.getUser();
        logs.info("【修改角色】当前用户信息:{}", info);
        Long belongId = info.getBelongId();
        String userType = info.getUserType();
        String userText = UserType.getText(userType);
        logs.info("【修改角色】当前用户所属ID:{},用户类型={}:{}", belongId, userType, userText);
        role.setBelongId(belongId);

        role.setUpdateBy(SystemContext.getUsername());
        Assert.isTrue((roleService.updateRole(role) > 0), "修改失败");
        // 更新缓存用户权限
        LoginInfo loginUser = SystemContext.getUser();
        if (StringUtils.isNull(loginUser) || loginUser.isAdmin()) {
            return;
        }
        SysUserDO user = BaseCache.getUser(loginUser.getUserId());
        loginUser.setPermissions(permissionService.getMenuPermission(user));
        //loginUser.setUser(userService.selectUserByUserName(user.getUserName()));
        tokenService.setLoginUser(loginUser);
    }

    /**
     * @param ids 角色信息ID数组
     * @Title delete
     * @Intro 删除角色信息
     * @Date 2024-08-20 14:45:05.630
     */
    public void delete(Long... ids) {
        Assert.isTrue(BeanUtils.isNotNull(ids), "删除失败");
        for (Long id : ids) {
            Assert.isTrue((roleService.deleteRoleById(id) > 0), "删除失败");
        }
    }
}